package com.bringspring.system.base.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.emoji.EmojiUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.model.login.BaseSystemInfo;
import com.bringspring.common.util.*;
import com.bringspring.common.util.treeutil.SumTree;
import com.bringspring.common.util.treeutil.newtreeutil.TreeDotUtils;
import com.bringspring.system.base.exception.WxErrorException;
import com.bringspring.system.base.model.dingding.DingDeptModel;
import com.bringspring.system.base.model.dingding.DingUserIdModel;
import com.bringspring.system.base.model.dingding.DingUserModel;
import com.bringspring.system.base.model.link.WeChatDepartment;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.base.util.aes.QyWxConfig;
import com.bringspring.system.message.entity.SynThirdInfoEntity;
import com.bringspring.system.message.model.message.OraganizeListVO;
import com.bringspring.system.message.model.message.SynThirdInfoCrForm;
import com.bringspring.system.message.model.message.SynThirdInfoUpForm;
import com.bringspring.system.message.service.SynThirdDingTalkService;
import com.bringspring.system.message.service.SynThirdInfoService;
import com.bringspring.system.message.service.SynThirdQyService;
import com.bringspring.system.message.util.SynDingTalkUtil;
import com.bringspring.system.message.util.SynQyWebChatUtil;
import com.bringspring.system.message.util.SynThirdConsts;
import com.bringspring.system.message.util.SynThirdTotal;
import com.bringspring.system.permission.entity.*;
import com.bringspring.system.permission.model.organize.OrganizeModel;
import com.bringspring.system.permission.service.*;
import com.bringspring.system.permission.util.BaseDataUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiUserListidRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.open.app.api.GenericEventListener;
import com.dingtalk.open.app.api.OpenDingTalkStreamClientBuilder;
import com.dingtalk.open.app.api.message.GenericOpenDingTalkEvent;
import com.dingtalk.open.app.api.security.AuthClientCredential;
import com.dingtalk.open.app.stream.protocol.event.EventAckStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.apdplat.word.segmentation.Word;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.validation.Valid;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.text.ParseException;
import java.util.*;

import static com.bringspring.system.message.util.SynThirdConsts.*;
import static com.bringspring.system.permission.constant.PermissionConst.*;
import static org.apdplat.word.tagging.PinyinTagging.process;

/**
 * 第三方工具的公司-部门-用户同步表模型
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2021/4/25 9:30
 */
@Slf4j
@Api(tags = "第三方信息同步", value = "SynThirdInfo")
@RestController
@RequestMapping("/api/system/SynThirdInfo")
public class SynThirdInfoController {
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SynThirdInfoService synThirdInfoService;
    @Autowired
    private SynThirdQyService synThirdQyService;
    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    PositionService positionService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRelationService userRelationService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BaseDataUtil baseDataUtil;

    @Autowired
    QyWxConfig qyWxConfig;

    @Autowired
    private SysConfigService sysConfigService;

//    @Autowired
//    private DIngStream dIngStream;

    private WxCpService wxCpService;

    /**
     * 新增同步表信息
     *
     * @param synThirdInfoCrForm 新建模型
     * @return ignore
     */
    @ApiOperation("新增同步表信息")
    @PostMapping
    @DSTransactional
    public ActionResult create(@RequestBody @Valid SynThirdInfoCrForm synThirdInfoCrForm) throws DataException {
        UserInfo userInfo = userProvider.get();
        SynThirdInfoEntity entity = JsonUtil.getJsonToBean(synThirdInfoCrForm, SynThirdInfoEntity.class);
        entity.setCreatorUserId(userInfo.getUserId());
        entity.setCreatorTime(DateUtil.getNowDate());
        entity.setId(RandomUtil.uuId());
        synThirdInfoService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 获取同步表信息
     *
     * @param id 主键
     * @return ignore
     */
    @ApiOperation("获取同步表信息")
    @GetMapping("/{id}")
    public SynThirdInfoEntity getInfo(@PathVariable("id") String id) {
        SynThirdInfoEntity entity = synThirdInfoService.getInfo(id);
        return entity;
    }

    /**
     * 获取指定类型的同步对象
     *
     * @param thirdType 1:企业微信 2:钉钉
     * @param dataType  1:公司 2:部门 3：用户
     * @param id        dataType对应的对象ID
     * @return ignore
     */
    @ApiOperation("获取指定类型的同步对象")
    @GetMapping("/getInfoBySysObjId/{thirdType}/{dataType}/{id}")
    public SynThirdInfoEntity getInfoBySysObjId(@PathVariable("thirdType") String thirdType, @PathVariable("dataType") String dataType, @PathVariable("id") String id) {
        SynThirdInfoEntity entity = synThirdInfoService.getInfoBySysObjId(thirdType, dataType, id);
        return entity;
    }


    /**
     * 更新同步表信息
     *
     * @param id                 主键
     * @param synThirdInfoUpForm 修改对象
     * @return ignore
     * @throws DataException ignore
     */
    @ApiOperation("更新同步表信息")
    @PutMapping("/{id}")
    @DSTransactional
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid SynThirdInfoUpForm synThirdInfoUpForm) throws DataException {
        SynThirdInfoEntity entity = synThirdInfoService.getInfo(id);
        UserInfo userInfo = userProvider.get();
        if (entity != null) {
            SynThirdInfoEntity entityUpd = JsonUtil.getJsonToBean(synThirdInfoUpForm, SynThirdInfoEntity.class);
            entityUpd.setCreatorUserId(entity.getCreatorUserId());
            entityUpd.setCreatorTime(entity.getCreatorTime());
            entityUpd.setLastModifyUserId(userInfo.getUserId());
            entityUpd.setLastModifyTime(DateUtil.getNowDate());
            synThirdInfoService.update(id, entityUpd);

            return ActionResult.success(MsgCode.SU004.get());
        } else {
            return ActionResult.fail(MsgCode.FA002.get());
        }
    }


    /**
     * 删除同步表信息
     *
     * @param id 主键
     * @return ignore
     */
    @ApiOperation("删除同步表信息")
    @DeleteMapping("/{id}")
    @DSTransactional
    public ActionResult delete(@PathVariable("id") String id) {
        SynThirdInfoEntity entity = synThirdInfoService.getInfo(id);
        if (entity != null) {
            synThirdInfoService.delete(entity);
        }
        return ActionResult.success(MsgCode.SU003.get());
    }


    /**
     * 获取第三方(如：企业微信、钉钉)的组织与用户同步统计信息
     *
     * @param thirdType 第三方类型(1:企业微信;2:钉钉)
     * @return ignore
     */
    @ApiOperation("获取第三方(如：企业微信、钉钉)的组织与用户同步统计信息")
    @GetMapping("/getSynThirdTotal/{thirdType}")
    public ActionResult getSynThirdTotal(@PathVariable("thirdType") String thirdType) {
        List<SynThirdTotal> synTotalList = new ArrayList<>();
        synTotalList.add(synThirdInfoService.getSynTotal(thirdType, DATA_TYPE_ORG));
        synTotalList.add(synThirdInfoService.getSynTotal(thirdType, DATA_TYPE_USER));
        return ActionResult.success(synTotalList);
    }

    /**
     * 获取第三方(如：企业微信、钉钉)的组织或用户同步统计信息
     *
     * @param thirdType 第三方类型(1:企业微信;2:钉钉)
     * @param dataType  数据类型(1:组织(公司与部门);2:用户)
     * @return ignore
     */
    @ApiOperation("获取第三方(如：企业微信、钉钉)的组织或用户同步统计信息")
    @GetMapping("/getSynThirdTotal/{thirdType}/{dataType}")
    public SynThirdTotal getSynThirdTotal(@PathVariable("thirdType") String thirdType, @PathVariable("dataType") String dataType) {
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(thirdType, dataType);
        return synThirdTotal;
    }

    /**
     * 本地所有组织信息(包含公司和部门)同步到企业微信
     * 不带第三方错误定位判断的功能代码,只获取调用接口的返回信息 20210604
     *
     * @return ignore
     * @throws WxErrorException ignore
     */
    @ApiOperation("本地所有组织信息(包含公司和部门)同步到企业微信")
    @PostMapping("/synAllOrganizeSysToQy")
    public ActionResult synAllOrganizeSysToQy(@RequestBody BaseSystemInfo config) throws WxErrorException {
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        String corpId = config.getQyhCorpId();
        String corpSecret = config.getQyhCorpSecret();
        String access_token = "";
        try {
            // 获取Token值
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            access_token = tokenObject.getString("access_token");
            WxCpDepart depart = new WxCpDepart();
// 部门Id必须有值,不能为空
            Long departId = Long.valueOf(2);
            depart.setId(departId);

// 为要修改的字段赋值
            depart.setName("子部门改名" + System.currentTimeMillis());

//            this.wxCpService.getDepartmentService().update(depart);
            // 获取同步表、部门表的信息
            List<SynThirdInfoEntity> synThirdInfoList = synThirdInfoService.getListByCrop(THIRD_TYPE_QY, DATA_TYPE_ORG, corpId);
            List<OrganizeEntity> organizeList = organizeService.getList();

            // 部门进行树结构化,固化上下层级序列化
            List<OrganizeModel> organizeModelList = JsonUtil.getJsonToList(organizeList, OrganizeModel.class);
            List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(organizeModelList);
            List<OraganizeListVO> listVO = JsonUtil.getJsonToList(trees, OraganizeListVO.class);

            // 转化成为按上下层级顺序排序的列表数据
            List<OrganizeEntity> listByOrder = new ArrayList<>();
            for (OraganizeListVO organizeVo : listVO) {
                OrganizeEntity entity = organizeList.stream().filter(t -> t.getId().equals(organizeVo.getId())).findFirst().orElse(null);
                listByOrder.add(entity);
                SynQyWebChatUtil.getOrganizeTreeToList(organizeVo, organizeList, listByOrder);
            }

            // 根据同步表、公司表进行比较，判断不存的执行删除
//            for (SynThirdInfoEntity synThirdInfoEntity : synThirdInfoList) {
//                if (organizeList.stream().filter(t -> t.getId().equals(synThirdInfoEntity.getSystemObjectId())).count() == 0 ? true : false) {
//                    //执行删除操作
//                    retMsg = synThirdQyService.deleteDepartmentSysToQy(true, synThirdInfoEntity.getSystemObjectId(), access_token);
//                }
//            }

            synThirdInfoList = synThirdInfoService.getListByCrop(THIRD_TYPE_QY, DATA_TYPE_ORG, config.getQyhCorpId());
            // 根据公司表、同步表进行比较，决定执行创建、还是更新
            for (OrganizeEntity organizeEntity : listByOrder) {
                if (synThirdInfoList.stream().filter(t -> t.getSystemObjectId().equals(organizeEntity.getId())).count() > 0 ? true : false) {
                    // 执行更新功能
                    retMsg = synThirdQyService.updateDepartmentSysToQy(true, organizeEntity, access_token, config);
                } else {
                    // 执行创建功能
                    retMsg = synThirdQyService.createDepartmentSysToQy(true, organizeEntity, access_token);
                }
            }
        } catch (Exception e) {
            ActionResult.fail(e.toString());
        }
        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(THIRD_TYPE_QY, DATA_TYPE_ORG);
        return ActionResult.success(synThirdTotal);
    }


    /**
     * 本地所有用户信息同步到企业微信
     * 不带第三方错误定位判断的功能代码,只获取调用接口的返回信息 20210604
     *
     * @return ignore
     * @throws WxErrorException ignore
     */
    @ApiOperation("本地所有用户信息同步到企业微信")
    @GetMapping("/synAllUserSysToQy")
    public ActionResult synAllUserSysToQy() throws WxErrorException {
        JSONObject retMsg = new JSONObject();
        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        String corpId = config.getQyhCorpId();
        String corpSecret = config.getQyhCorpSecret();
        String access_token = "";

        try {
            // 获取Token值
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            access_token = tokenObject.getString("access_token");

            // 获取同步表、用户表的信息
            List<SynThirdInfoEntity> synThirdInfoList = synThirdInfoService.getList(THIRD_TYPE_QY, DATA_TYPE_USER);
            List<UserEntity> userList = userService.getList();

            // 根据同步表、公司表进行比较，判断不存的执行删除
            for (SynThirdInfoEntity synThirdInfoEntity : synThirdInfoList) {
                if (userList.stream().filter(t -> t.getId().equals(synThirdInfoEntity.getSystemObjectId())).count() == 0 ? true : false) {
                    //执行删除操作
                    retMsg = synThirdQyService.deleteUserSysToQy(true, synThirdInfoEntity.getSystemObjectId(), access_token);
                }
            }

            // 根据公司表、同步表进行比较，决定执行创建、还是更新
            for (UserEntity userEntity : userList) {
                if (synThirdInfoList.stream().filter(t -> t.getSystemObjectId().equals(userEntity.getId())).count() == 0 ? true : false) {
                    // 执行创建功能
                    retMsg = synThirdQyService.createUserSysToQy(true, userEntity, access_token);
                } else {
                    // 执行更新功能
                    retMsg = synThirdQyService.updateUserSysToQy(true, userEntity, access_token);
                }
            }
        } catch (Exception e) {
            ActionResult.fail(e.toString());
        }

        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(THIRD_TYPE_QY, DATA_TYPE_USER);
        return ActionResult.success(synThirdTotal);
    }


    //==================================本系统的公司-部门-用户批量同步到钉钉==================================

    /**
     * 本地所有组织信息(包含公司和部门)同步到钉钉
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("本地所有组织信息(包含公司和部门)同步到钉钉")
    @PostMapping("/synAllOrganizeSysToDing")
    public ActionResult synAllOrganizeSysToDing(@RequestBody BaseSystemInfo config) {
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdDingTalkService.getDingTalkConfig();
//        String corpId = config.getDingSynAppKey();
//        String corpSecret = config.getDingSynAppSecret();
        String corpId = config.getClientId();
        String corpSecret = config.getClientSecrent();
        try {
            // 获取Token值
            JSONObject tokenObject = SynDingTalkUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取钉钉的access_token失败");
            }
            String access_token = tokenObject.getString("access_token");

            // 获取同步表、部门表的信息
            List<SynThirdInfoEntity> synThirdInfoList = synThirdInfoService.getList(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
            List<OrganizeEntity> organizeList = organizeService.getList();

            // 部门进行树结构化,固化上下层级序列化
            List<OrganizeModel> organizeModelList = JsonUtil.getJsonToList(organizeList, OrganizeModel.class);
            List<SumTree<OrganizeModel>> trees = TreeDotUtils.convertListToTreeDot(organizeModelList);
            List<OraganizeListVO> listVO = JsonUtil.getJsonToList(trees, OraganizeListVO.class);

            // 转化成为按上下层级顺序排序的列表数据
            List<OrganizeEntity> listByOrder = new ArrayList<>();
            for (OraganizeListVO organizeVo : listVO) {
                OrganizeEntity entity = organizeList.stream().filter(t -> t.getId().equals(organizeVo.getId())).findFirst().orElse(null);
                listByOrder.add(entity);
                SynDingTalkUtil.getOrganizeTreeToList(organizeVo, organizeList, listByOrder);
            }

            // 根据同步表、公司表进行比较，判断不存的执行删除
            for (SynThirdInfoEntity synThirdInfoEntity : synThirdInfoList) {
                if (organizeList.stream().filter(t -> t.getId().equals(synThirdInfoEntity.getSystemObjectId())).count() == 0 ? true : false) {
                    //执行删除操作
                    retMsg = synThirdDingTalkService.deleteDepartmentSysToDing(true, synThirdInfoEntity.getSystemObjectId(), access_token);
                }
            }

            synThirdInfoList = synThirdInfoService.getList(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
            // 根据公司表、同步表进行比较，决定执行创建、还是更新
            for (OrganizeEntity organizeEntity : listByOrder) {
                if (synThirdInfoList.stream().filter(t -> t.getSystemObjectId().equals(organizeEntity.getId())).count() > 0 ? true : false) {
                    // 执行更新功能
                    retMsg = synThirdDingTalkService.updateDepartmentSysToDing(true, organizeEntity, access_token);
                } else {
                    // 执行创建功能
                    retMsg = synThirdDingTalkService.createDepartmentSysToDing(true, organizeEntity, access_token);
                }
            }
        } catch (Exception e) {
            ActionResult.fail(e.toString());
        }

        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
        return ActionResult.success(synThirdTotal);
    }


    /**
     * 本地所有用户信息同步到钉钉
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("本地所有用户信息同步到钉钉")
    @PostMapping("/synAllUserSysToDing")
    public ActionResult synAllUserSysToDing(@RequestBody BaseSystemInfo config) throws ParseException {
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdDingTalkService.getDingTalkConfig();
        String corpId = config.getClientId();
        String corpSecret = config.getClientSecrent();

        try {
            // 获取Token值
            JSONObject tokenObject = SynDingTalkUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.success("获取钉钉的access_token失败");
            }
            String access_token = tokenObject.getString("access_token");

            // 获取同步表、用户表的信息
            List<SynThirdInfoEntity> synThirdInfoList = synThirdInfoService.getList(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_USER);
            List<UserEntity> userList = userService.getList();

            // 根据同步表、公司表进行比较，判断不存的执行删除
            for (SynThirdInfoEntity synThirdInfoEntity : synThirdInfoList) {
                if (userList.stream().filter(t -> t.getId().equals(synThirdInfoEntity.getSystemObjectId())).count() == 0 ? true : false) {
                    // 执行删除操作
                    retMsg = synThirdDingTalkService.deleteUserSysToDing(true, synThirdInfoEntity.getSystemObjectId(), access_token);
                }
            }

            // 根据公司表、同步表进行比较，决定执行创建、还是更新
            for (UserEntity userEntity : userList) {
                if (synThirdInfoList.stream().filter(t -> t.getSystemObjectId().equals(userEntity.getId())).count() == 0 ? true : false) {
                    // 执行创建功能
                    retMsg = synThirdDingTalkService.createUserSysToDing(true, userEntity, access_token);
                } else {
                    // 执行更新功能
                    retMsg = synThirdDingTalkService.updateUserSysToDing(true, userEntity, access_token);
                }
            }
        } catch (Exception e) {
            ActionResult.fail(e.toString());
        }

        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_USER);
        return ActionResult.success(synThirdTotal);
    }


    /**
     * 企业微信单个组织信息(包含公司和部门)同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信单个组织信息(包含公司和部门)同步到本地")
    @GetMapping("/synQyToOrganizeSys")
    public ActionResult synQyToOrganizeSys(String id, String companyId) throws Exception {

        synThirdQyService.synQyToOrganizeSys(id, companyId);
        return ActionResult.success(null);
    }


    /**
     * 企业微信单个用户同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信单个用户同步到本地")
    @GetMapping("/synQyToUserSys")
    public ActionResult synQyToUserSys(String id, String companyId) throws Exception {
        synThirdQyService.synQyToUserSys(id, companyId);
        return ActionResult.success(null);
    }

    /**
     * 企业微信所有组织信息(包含公司和部门)同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信所有组织信息(包含公司和部门)同步到本地")
    @PostMapping("/synQyToAllOrganizeSys")
    public ActionResult synQyToAllOrganizeSys(@RequestBody BaseSystemInfo config) {
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        String corpId = config.getQyhCorpId();
        String corpSecret = config.getQyhCorpSecret();
        String access_token = "";
        UserInfo userInfo = userProvider.get();
        try {
            // 获取Token值
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            access_token = tokenObject.getString("access_token");
            // 获取微信企业部门
            JSONObject departmentList = SynQyWebChatUtil.getDepartmentList(null, access_token);
            List<OrganizeEntity> departmentQy = new ArrayList<OrganizeEntity>();
            JSONObject jo = JSONObject.parseObject(String.valueOf(departmentList));
            String department = String.valueOf(jo.get("department"));
            List<Map<String, Object>> jsonToListMap = JsonUtil.getJsonToListMap(department);
            // 获取本地部门
            List<OrganizeEntity> listOrgan = organizeService.getList();
            //  本地有的编辑，本地没有的新增
//            if (listOrgan.size() > 0) {
            String organize = "";
            for (Map organizeEntity : jsonToListMap) {
                OrganizeEntity organizeEntityQy = new OrganizeEntity();
                organizeEntityQy.setId(corpId + organizeEntity.get("id"));
                organizeEntityQy.setFullName(String.valueOf(organizeEntity.get("name")));
                organizeEntityQy.setParentId(corpId + organizeEntity.get("parentid"));
                organizeEntityQy.setSortCode(Long.valueOf(Long.valueOf(String.valueOf(organizeEntity.get("order")))));
                organizeEntityQy.setManagerId(String.valueOf(organizeEntity.get("department_leader")).replaceAll("\\[", "").replaceAll("]", "").replaceAll("\"", ""));
                organizeEntityQy.setCategory("department");
                if ("1".equals(String.valueOf(organizeEntity.get("id")))) {
                    organizeEntityQy.setCategory("company");
                    organizeEntityQy.setEnCode("R");
//                    organizeEntityQy.setParentId(!ObjectUtil.isEmpty(config.getOrgParent()) ? config.getOrgParent() : "0");
                    organizeEntityQy.setParentId("0");
                    organize = corpId + organizeEntity.get("id");
                } else {
                    organizeEntityQy.setCategory("department");
                }
                organizeEntityQy.setOrganizeId(organize);
//                departmentQy.add(organizeEntityQy);
                if (listOrgan.stream().filter(t -> t.getId().equals(String.valueOf(organizeEntityQy.getId()))).count() == 0) {
                    // 新增
//                    synThirdQyService.createOrgan(organizeEntityQy);
                    SynThirdInfoEntity synThirdInfoEntity = new SynThirdInfoEntity();
                    synThirdInfoEntity.setThirdObjectId(String.valueOf(organizeEntity.get("id")));
                    synThirdInfoEntity.setSystemObjectId(String.valueOf(organizeEntityQy.getId()));
                    synThirdInfoEntity.setThirdType(Integer.valueOf(THIRD_TYPE_QY));
                    synThirdInfoEntity.setDataType(Integer.valueOf(DATA_TYPE_ORG));
                    synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK);
                    synThirdInfoEntity.setCreatorUserId(userInfo.getUserId());
                    synThirdInfoEntity.setCreatorTime(DateUtil.getNowDate());
                    synThirdInfoEntity.setId(RandomUtil.uuId());
                    synThirdInfoEntity.setCropId(corpId);
                    synThirdInfoService.saveOrUpdate(synThirdInfoEntity);
                } else {
                    //  编辑
//                    boolean update = organizeService.update(String.valueOf(organizeEntityQy.getId()), organizeEntityQy);
                }
                departmentQy.add(organizeEntityQy);
            }
            organizeService.saveOrUpdateBatch(departmentQy);
        } catch (Exception e) {
            ActionResult.fail(e.toString());
        }
//        dIngStream.setOrganizeCode();
//        dIngStream.setOrganizedTree();
        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
        return ActionResult.success(synThirdTotal);
    }

    /**
     * 钉钉所有组织信息(包含公司和部门)同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("钉钉所有组织信息(包含公司和部门)同步到本地")
    @PostMapping("/synDingToAllOrganizeSys")
    public ActionResult synDingToAllOrganizeSys(@RequestBody BaseSystemInfo config) throws Exception {
        DingTalkClient clientToken = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(config.getQyhCorpId());
        req.setAppsecret(config.getQyhCorpSecret());
        req.setHttpMethod("GET");
        OapiGettokenResponse rsp = clientToken.execute(req);
        System.out.println(rsp.getBody());
        Map<String, Object> stringObjectMap = JsonUtil.stringToMap(rsp.getBody());
        if (!stringObjectMap.containsKey("access_token")) {
            throw new Exception("获取钉钉access_token失败");
        }
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiGettokenResponse execute = client.execute(req, String.valueOf(stringObjectMap.get("access_token")));
        System.out.println(execute.getBody());
        List<DingDeptModel> resultDepart = JsonUtil.getJsonToList(String.valueOf(JsonUtil.stringToMap(execute.getBody()).get("result")), DingDeptModel.class);
        // 有的新增，没有的编辑。
//        return dIngStream.orgAOD(resultDepart, config.getQyhCorpId());
        return null;
    }

    /**
     * 钉钉所有用户同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("钉钉所有用户同步到本地")
    @PostMapping("/synDingToAllUserSys")
    public ActionResult synDingToAllUserSys(@RequestBody BaseSystemInfo config) throws Exception {
        String qyhCorpId = config.getQyhCorpId();
        DingTalkClient clientToken = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(qyhCorpId);
        req.setAppsecret(config.getQyhCorpSecret());
        req.setHttpMethod("GET");
        OapiGettokenResponse rsp = clientToken.execute(req);
        System.out.println(rsp.getBody());
        Map<String, Object> stringObjectMap = JsonUtil.stringToMap(rsp.getBody());
        if (!stringObjectMap.containsKey("access_token")) {
            throw new Exception("获取钉钉access_token失败");
        }
        String accessToken = String.valueOf(stringObjectMap.get("access_token"));
        // 获取部门列表
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiGettokenResponse execute = client.execute(req, accessToken);
        System.out.println(execute.getBody());
        List<DingDeptModel> resultDepart = new ArrayList<>();
        DingDeptModel dingDeptModelPar = new DingDeptModel();
        dingDeptModelPar.setDept_id("1");
        resultDepart.add(dingDeptModelPar);
        resultDepart.addAll(JsonUtil.getJsonToList(String.valueOf(JsonUtil.stringToMap(execute.getBody()).get("result")), DingDeptModel.class));
        List<DingUserModel> resultUserList = new ArrayList<>();
        List<RoleEntity> listByEnCode = roleService.getListByEnCode(SIMPLE_USER);
        List<SynThirdInfoEntity> listThird = synThirdInfoService.getList(THIRD_TYPE_QY, DATA_TYPE_USER);
        UserInfo userInfo = userProvider.get();
        // 获取部门下人员id
        if (!ObjectUtil.isEmpty(resultDepart)) {
            for (int i = 0; i < resultDepart.size(); i++) {
                DingDeptModel dingDeptModel = resultDepart.get(i);
                DingTalkClient clientUserId = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
                OapiUserListidRequest reqUserId = new OapiUserListidRequest();
                reqUserId.setDeptId(Long.valueOf(dingDeptModel.getDept_id()));
                OapiUserListidResponse rspUserId = clientUserId.execute(reqUserId, accessToken);
                System.out.println(rspUserId.getBody());
                DingUserIdModel resultId = JsonUtil.getJsonToBean(String.valueOf(JsonUtil.stringToMap(rspUserId.getBody()).get("result")), DingUserIdModel.class);
                if (!ObjectUtil.isEmpty(resultId)) {
                    DingTalkClient clientUser = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
                    OapiV2UserGetRequest reqUser = new OapiV2UserGetRequest();
                    reqUser.setUserid("141410123526265934");
                    OapiV2UserGetResponse rspUser = clientUser.execute(reqUser, accessToken);
                    DingUserModel resultUser = JsonUtil.getJsonToBean(String.valueOf(JsonUtil.stringToMap(rspUser.getBody()).get("result")), DingUserModel.class);
                    resultUser.setDepartmentId(dingDeptModel.getDept_id());
                    System.out.println(rsp.getBody());
//                    dIngStream.userAOD(resultUser.getUserid(), qyhCorpId);
                    resultUserList.add(resultUser);
                }
            }
        }
//        if (!ObjectUtil.isEmpty(resultUserList)) {
//            for (DingUserModel map : resultUserList) {
//                UserEntity userEntity = new UserEntity();
//                String userid = String.valueOf(map.getUserid());
//                SynThirdInfoEntity synThirdInfoEntity = new SynThirdInfoEntity();
//                // 账户用userID id
//                if (!StringUtils.isNull(map.getUserid())) {
//                    List<SynThirdInfoEntity> first = listThird.stream().filter(n -> userid.equals(n.getThirdObjectId())).collect(Collectors.toList());
//                    if (!ObjectUtil.isEmpty(first)) {
//                        synThirdInfoEntity = first.get(0);
//                        if (null != synThirdInfoEntity) {
//                            userEntity.setId(synThirdInfoEntity.getSystemObjectId());
//                        } else {
//                            userEntity.setId(RandomUtil.uuId());
//                            synThirdInfoEntity = new SynThirdInfoEntity();
//                            synThirdInfoEntity.setId(RandomUtil.uuId());
//                        }
//                    }
//                }
//                // 判断是不是为空,需要挨个判断。
//                if (!StringUtils.isNull(map.getName())) {
//                    userEntity.setRealName(map.getName().replaceAll("[^\u4e00-\u9fa5]", ""));
//                }
//
//                // 昵称
//                if (!StringUtils.isNull(map.getNickname())) {
//                    userEntity.setNickName(map.getNickname());
//                }
//                // 账户用userID id
//                if (!StringUtils.isNull(map.getUserid())) {
//                    userEntity.setAccount(map.getUserid());
//                }
//                if (!StringUtils.isNull(map.getDepartmentId())) {
//                    userEntity.setOrganizeId(map.getDepartmentId());
//                }
//                if (!StringUtils.isNull(map.getMobile())) {
//                    userEntity.setMobilePhone(map.getMobile());
//                }
//                if (!StringUtils.isNull(map.getEmail())) {
//                    userEntity.setEmail(map.getEmail());
//                }
//                if (!StringUtils.isNull(map.getWork_place())) {
//                    userEntity.setPostalAddress(map.getWork_place());
//                }
//                userEntity.setGender(3);
//                if (!StringUtils.isNull(map.getManager_userid())) {
//                    userEntity.setManagerId(map.getManager_userid());
//                }
////                        if (!StringUtils.isNull(map.get("position"))) {
////                            userEntity.setPositionId(String.valueOf(map.get("position")));
////                        }
//                //获取头像  微信企业没传，暂定为默认
//                userEntity.setHeadIcon("/api/file/Image/userAvatar/001.png");
//                userEntity.setEnabledMark(1);
//                userEntity.setRoleId(listByEnCode.get(0).getId());
//                // 自定义员工编号，根据组织id获取所属公司。
//                OrganizeEntity orgInfo = organizeService.getInfo(map.getDepartmentId());
//                if (ObjectUtil.isNotEmpty(orgInfo)) {
//                    OrganizeEntity companyInfo = organizeService.getInfo(orgInfo.getOrganizeId());
//                    if (!ObjectUtil.isEmpty(companyInfo)) {
//                        String enCode = companyInfo.getEnCode() + "Staff";
//                        String billNumber = baseDataUtil.getBillNumber(enCode, false);
//                        userEntity.setCode(billNumber);
//                    }
//                }
//                List<SynThirdInfoEntity> infoByThirdObjIds = synThirdInfoService.getInfoByThirdObjIds(SynThirdConsts.THIRD_TYPE_DING, SynThirdConsts.DATA_TYPE_USER, map.getUserid());
//                if (ObjectUtil.isEmpty(infoByThirdObjIds)) {
//                    userService.createUser(userEntity);
//                    synThirdInfoEntity.setThirdObjectId(String.valueOf(map.getUserid()));
//                    synThirdInfoEntity.setSystemObjectId(userEntity.getId());
//                    synThirdInfoEntity.setThirdType(Integer.valueOf(SynThirdConsts.THIRD_TYPE_DING));
//                    synThirdInfoEntity.setDataType(Integer.valueOf(SynThirdConsts.DATA_TYPE_USER));
//                    synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK);
//                    synThirdInfoEntity.setCropId(qyhCorpId);
//                    synThirdInfoEntity.setCreatorUserId(userInfo.getUserId());
//                    synThirdInfoEntity.setCreatorTime(DateUtil.getNowDate());
//                    synThirdInfoService.saveOrUpdate(synThirdInfoEntity);
//                } else {
//                    //  编辑
//                    userEntity.setId(infoByThirdObjIds.get(0).getSystemObjectId());
//                    boolean update = userService.updateById(userEntity);
//                }
//            }
//        }

        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
        return ActionResult.success(synThirdTotal);
    }

    /**
     * 企业微信所有用户同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信所有用户同步到本地")
    @PostMapping("/synQyToAllUserSys")
    public ActionResult synQyToAllUserSys(@RequestBody BaseSystemInfo config) {
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        String corpId = config.getQyhCorpId();
        String corpSecret = config.getQyhCorpSecret();
        String access_token = "";
        UserInfo userInfo = userProvider.get();
        try {
            // 获取Token值
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            access_token = tokenObject.getString("access_token");
            // 先获取本地企业部门，再根据本地部门获取成员、
            // 获取本地部门
            List<UserEntity> jsonToListMap = new ArrayList<>();
//            List<OrganizeEntity> listOrgan = organizeService.getList();
            List<SynThirdInfoEntity> listOrgan = synThirdInfoService.getListByCrop(THIRD_TYPE_QY, DATA_TYPE_ORG, corpId);
            //  获取本地成员
//            List<UserEntity> listUser = userService.getList();
            List<SynThirdInfoEntity> listUser = synThirdInfoService.getListByCrop(THIRD_TYPE_QY, DATA_TYPE_USER, corpId);
            //设置默认角色
            List<RoleEntity> listByEnCode = roleService.getListByEnCode(SIMPLE_USER);
            if (listOrgan.size() > 0) {
                for (SynThirdInfoEntity organizeEntity : listOrgan) {
                    JSONObject departmentList = SynQyWebChatUtil.getUserDetailList(String.valueOf(organizeEntity.getThirdObjectId()), "0", access_token);
                    JSONObject jo = JSONObject.parseObject(String.valueOf(departmentList));
                    String userlist = String.valueOf(jo.get("userlist"));
                    if (StringUtils.isNotEmpty(userlist)) {
                        List<Map<String, Object>> jsonToListMap1 = JsonUtil.getJsonToListMap(userlist);
                        for (Map map : jsonToListMap1) {
                            UserEntity userEntity = new UserEntity();
                            String userid = String.valueOf(map.get("userid"));
                            SynThirdInfoEntity synThirdInfoEntity = new SynThirdInfoEntity();
                            // 账户用userID id
                            if (!StringUtils.isNull(map.get("userid"))) {
                                List<SynThirdInfoEntity> synThirdInfoEntityList = synThirdInfoService.getInfoByThirdObjIds(THIRD_TYPE_QY, DATA_TYPE_USER, userid);
                                if (!ObjectUtil.isEmpty(synThirdInfoEntity.getId())) {
                                    userEntity.setId(synThirdInfoEntityList.get(0).getSystemObjectId());
                                } else {
                                    userEntity.setId(RandomUtil.uuId());
                                    synThirdInfoEntity = new SynThirdInfoEntity();
                                    synThirdInfoEntity.setId(RandomUtil.uuId());
                                }
                            }
                            // 判断是不是为空,需要挨个判断。
                            if (!StringUtils.isNull(map.get("name"))) {
                                userEntity.setRealName(String.valueOf(map.get("name")).replaceAll("[^\u4e00-\u9fa5]", ""));
                            }

                            // 快速查询
                            if (!StringUtils.isNull(map.get("lias"))) {
                                userEntity.setQuickQuery(String.valueOf(map.get("lias")));
                            }
                            // 昵称
                            if (!StringUtils.isNull(map.get("lias"))) {
                                userEntity.setNickName(String.valueOf(map.get("lias")));
                            }
                            // 账户用userID id
                            if (!StringUtils.isNull(map.get("userid"))) {
                                userEntity.setAccount(String.valueOf(map.get("userid")));
                            }
                            if (!StringUtils.isNull(map.get("department"))) {
                                String department1 = String.valueOf(map.get("department")).replaceAll("\\[", "").replaceAll("]", "");
                                userEntity.setOrganizeId(corpId + department1);
                            }
                            if (!StringUtils.isNull(map.get("mobile"))) {
                                userEntity.setMobilePhone(String.valueOf(map.get("mobile")));
                            }
                            if (!StringUtils.isNull(map.get("email"))) {
                                userEntity.setEmail(String.valueOf(map.get("email")));
                            }
                            if (!StringUtils.isNull(map.get("address"))) {
                                userEntity.setPostalAddress(String.valueOf(map.get("address")));
                            }
                            if (!StringUtils.isNull(map.get("gender")) && !"0".equals(String.valueOf(map.get("address")))) {
                                userEntity.setGender(Integer.parseInt(String.valueOf(map.get("address"))));
                            } else {
                                userEntity.setGender(3);
                            }
                            if (!StringUtils.isNull(map.get("direct_leader"))) {
                                userEntity.setManagerId(String.valueOf(map.get("direct_leader")).replaceAll("\\[", "").replaceAll("]", ""));
                            }

                            if (!StringUtils.isNull(map.get("position"))) {
                                userEntity.setPositionId(String.valueOf(map.get("position")));
                            }
                            //获取头像  微信企业没传，暂定为默认
                            userEntity.setHeadIcon("/api/file/Image/userAvatar/001.png");
                            userEntity.setEnabledMark(1);
                            userEntity.setRoleId(listByEnCode.get(0).getId());
                            // 自定义员工编号，根据组织id获取所属公司。
                            if (ObjectUtil.isNotEmpty(organizeEntity.getSystemObjectId())) {
                                OrganizeEntity orgInfo = organizeService.getInfo(organizeEntity.getSystemObjectId());
                                if (!ObjectUtil.isEmpty(orgInfo)) {
                                    OrganizeEntity companyInfo = organizeService.getInfo(orgInfo.getOrganizeId());
                                    String enCode = companyInfo.getEnCode() + "Staff";
                                    String billNumber = baseDataUtil.getBillNumber(enCode, false);
                                    userEntity.setCode(billNumber);
                                }
                            }
                            jsonToListMap.add(userEntity);
                            if (listUser.stream().filter(t -> t.getThirdObjectId().equals(String.valueOf(userid))).count() == 0) {
                                userService.createUser(userEntity);
                            } else {
                                //  编辑
                                boolean update = userService.updateById(userEntity);
                            }

                            synThirdInfoEntity.setThirdObjectId(String.valueOf(map.get("userid")));
                            synThirdInfoEntity.setSystemObjectId(userEntity.getId());
                            synThirdInfoEntity.setThirdType(Integer.valueOf(THIRD_TYPE_QY));
                            synThirdInfoEntity.setDataType(Integer.valueOf(DATA_TYPE_USER));
                            synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK);
                            synThirdInfoEntity.setCropId(corpId);
                            synThirdInfoEntity.setCreatorUserId(userInfo.getUserId());
                            synThirdInfoEntity.setCreatorTime(DateUtil.getNowDate());
                            synThirdInfoService.saveOrUpdate(synThirdInfoEntity);
                        }
                    }
                }
            } else {

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //获取结果
        SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(SynThirdConsts.THIRD_TYPE_DING, DATA_TYPE_ORG);
        return ActionResult.success(synThirdTotal);
    }

    /**
     * 企业微信组织变更同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信组织变更同步到本地")
    @PostMapping("/synQyToOrgChange")
    public ActionResult synQyToOrgChange(@RequestBody File xmlFile) throws Exception {
//        File xmlFile = new File("C:\\Users\\Admin\\Desktop\\临时\\file.xml");
//        File xmlFile = new File("C:\\Users\\Admin\\Desktop\\临时\\file11.xml");
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(xmlFile);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        OrganizeEntity organizeEntity = new OrganizeEntity();
        String id = root.getElementsByTagName("Id").item(0).getTextContent();
        String Name = root.getElementsByTagName("Name").item(0).getTextContent();
        organizeEntity.setFullName(Name);
        // 三方表关联关联不到就新增
        SynThirdInfoEntity infoByThirdObjId = synThirdInfoService.getInfoByThirdObjId("1", "1", id);
        if (ObjectUtil.isEmpty(infoByThirdObjId)) {
            organizeService.create(organizeEntity);
        } else {
            organizeEntity.setId(infoByThirdObjId.getSystemObjectId());
            organizeService.updateById(organizeEntity);
        }
        return ActionResult.success(null);
    }


    /**
     * 企业微信变更同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信人员变更同步到本地")
    @PostMapping("/synQyToUserChange")
    public ActionResult synQyToUserChange(@RequestBody File xmlFile) throws Exception {
//        File xmlFile = new File("C:\\Users\\Admin\\Desktop\\临时\\file.xml");
//        File xmlFile = new File("C:\\Users\\Admin\\Desktop\\临时\\file11.xml");
        JSONObject retMsg = new JSONObject();
//        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = factory.newDocumentBuilder().parse(xmlFile);
        doc.getDocumentElement().normalize();
        Element root = doc.getDocumentElement();
        UserEntity userEntity = new UserEntity();
        String UserID = root.getElementsByTagName("UserID").item(0).getTextContent();
        String Name = root.getElementsByTagName("Name").item(0).getTextContent();
        String MainDepartment = root.getElementsByTagName("MainDepartment").item(0).getTextContent();
        String Mobile = root.getElementsByTagName("Mobile").item(0).getTextContent();
        String Status = root.getElementsByTagName("Status").item(0).getTextContent();
        userEntity.setRealName(Name);
        userEntity.setOrganizeId(MainDepartment);
        userEntity.setMobilePhone(Mobile);
        userEntity.setRealName(Name);
        userEntity.setEnabledMark("1".equals(Status) ? 1 : 0);
        // 三方表关联关联不到就新增
        SynThirdInfoEntity infoByThirdObjId = synThirdInfoService.getInfoByThirdObjId("1", "2", UserID);
        if (ObjectUtil.isEmpty(infoByThirdObjId)) {
            userService.create(userEntity);
        } else {
            userEntity.setId(infoByThirdObjId.getSystemObjectId());
            userService.updateById(userEntity);
        }
        return ActionResult.success(null);
    }


    /**
     * 企业微信所有【企业互联】组织同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信所有【企业互联】组织同步到本地")
    @GetMapping("/synQyToAllLinkedCorp")
    @DSTransactional
    public ActionResult synQyToAllLinkedCorp() {
        /**
         * 获取企业微信的配置信息
         */
        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        // 企业ID
        String corpId = config.getQyhCorpId();
        // 应用的凭证密钥
        String corpSecret = config.getQyhCorpSecret();
        UserInfo userInfo = userProvider.get();
        try {
            /**
             * 获取access_token
             */
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            String access_token = tokenObject.getString("access_token");

            /**
             * 获取应用的可见范围
             */
            // 接口请求结果
            JSONObject permListRes = SynQyWebChatUtil.getLinkedcorpAgent(access_token);
            if (!permListRes.getBoolean("code")) {
                return ActionResult.fail("获取应用的可见范围失败");
            }
            // 互联ID列表
            String agentPermList = String.valueOf(permListRes.get("department_ids"));
            JSONArray agentPermArr = JSON.parseArray(agentPermList);

            if (agentPermArr != null && agentPermArr.size() != 0) {
                List<OrganizeEntity> organizeList = new ArrayList<>();
                List<SynThirdInfoEntity> synThirdInfoList = new ArrayList<>();
                for (Object s : agentPermArr) {
                    /**
                     * 获取互联企业部门列表
                     */
                    // 接口请求结果
                    JSONObject departmentRes = SynQyWebChatUtil.getLinkedcorpDepartment(access_token, String.valueOf(s));
                    if (!departmentRes.getBoolean("code")) {
                        return ActionResult.fail("获取互联企业部门列表失败");
                    }
                    String departmentList = String.valueOf(departmentRes.get("departmentList"));
                    List<WeChatDepartment> jsonToList = JsonUtil.getJsonToList(departmentList, WeChatDepartment.class);
                    jsonToList.stream().forEach(item -> {
                        String id = item.getDepartment_id();
                        String parentid = item.getParentid();
                        //组织数据
                        OrganizeEntity organizeEntity = new OrganizeEntity();
                        // 创建的部门id
                        organizeEntity.setId(id);
                        // 部门名称
                        organizeEntity.setFullName(item.getDepartment_name());
                        // 父部门id。根部门为0 替换为 根部门为-1
                        organizeEntity.setParentId("0".equals(parentid) ? "-1" : parentid);
                        // 机构分类。根据父部门id 为0或1的机构分类为公司
                        organizeEntity.setCategory("1".equals(parentid) || "0".equals(parentid) ? "company" : "department");
                        // 排序
                        organizeEntity.setSortCode(item.getOrder());
                        organizeList.add(organizeEntity);

                        // THIRD_TYPE_QY：第三方工具类型(1:企业微信;2:钉钉)、DATA_TYPE_ORG：数据类型(1:组织(公司与部门);2:用户)
                        SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoByThirdObjId(THIRD_TYPE_QY,
                                DATA_TYPE_ORG, id);
                        if (null == synThirdInfoEntity) {
                            // 不存在 则创建。 “第三方工具的公司-部门-用户同步表模型”
                            synThirdInfoEntity = new SynThirdInfoEntity();
                            synThirdInfoEntity.setId(RandomUtil.uuId());
                        }
                        synThirdInfoEntity.setThirdObjectId(id); // 第三对象ID
                        synThirdInfoEntity.setSystemObjectId(id); // 系统对象ID
                        synThirdInfoEntity.setThirdType(Integer.valueOf(THIRD_TYPE_QY)); // 第三方类型(1:企业微信;2:钉钉)
                        synThirdInfoEntity.setDataType(Integer.valueOf(DATA_TYPE_ORG)); // 数据类型(1:组织(公司与部门);2:用户)
                        synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK); // 同步状态(0:未同步;1:同步成功;2:同步失败)
                        synThirdInfoEntity.setCreatorUserId(userInfo.getUserId()); // 创建人
                        synThirdInfoEntity.setCreatorTime(DateUtil.getNowDate()); // 创建时间
                        synThirdInfoList.add(synThirdInfoEntity);

                    });
                }
                if (organizeList.size() != 0 && synThirdInfoList.size() != 0) {
                    /**
                     * 本地有的编辑，本地没有的新增 saveBatch
                     * 批量新增或编辑
                     */
                    organizeService.saveOrUpdateBatch(organizeList);
                    synThirdInfoService.saveOrUpdateBatch(synThirdInfoList);
                    /**
                     * 机构编码为空的 设置机构编码
                     */
                    // dIngStream.setOrganizeCode();
                    /**
                     * 设置祖宗组织id
                     */
//                    dIngStream.setOrganizedTree();
                    //获取结果
                    SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(THIRD_TYPE_QY, DATA_TYPE_ORG);
                    return ActionResult.success(synThirdTotal);
                } else {
                    return ActionResult.fail("获取互联企业部门列表为空");
                }
            } else {
                return ActionResult.fail("获取应用的可见范围为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.fail("系统异常：" + e);
        }
    }


    /**
     * 企业微信【互联企业】所有用户同步到本地
     * 不带第三方错误定位判断的功能代码 20210604
     *
     * @return ignore
     */
    @ApiOperation("企业微信【互联企业】所有用户同步到本地")
    @GetMapping("/synQyLinkedToAllUserSys")
    @DSTransactional
    public ActionResult synQyLinkedToAllUserSys() {
        /**
         * 获取企业微信的配置信息
         */
        BaseSystemInfo config = synThirdQyService.getQyhConfig();
        // 企业ID
        String corpId = config.getQyhCorpId();
        // 应用的凭证密钥
        String corpSecret = config.getQyhCorpSecret();
        UserInfo userInfo = userProvider.get();
        try {
            /**
             * 获取access_token
             */
            JSONObject tokenObject = SynQyWebChatUtil.getAccessToken(corpId, corpSecret);
            if (!tokenObject.getBoolean("code")) {
                return ActionResult.fail("获取企业微信access_token失败");
            }
            String access_token = tokenObject.getString("access_token");

            /**
             * 获取应用的可见范围
             */
            // 接口请求结果
            JSONObject permListRes = SynQyWebChatUtil.getLinkedcorpAgent(access_token);
            if (!permListRes.getBoolean("code")) {
                return ActionResult.fail("获取应用的可见范围失败");
            }
            // 互联ID列表
            String agentPermList = String.valueOf(permListRes.get("department_ids"));
            JSONArray agentPermArr = JSON.parseArray(agentPermList);
            if (agentPermArr != null && agentPermArr.size() != 0) {
                String targetChar = "/"; // 目标字符
                String regexChar = ","; // 目标字符
                // 当前系统用户列表
                List<UserEntity> userList = userService.getList();
                Map<String, UserEntity> accountMap = new HashMap<>();
                Map<String, UserEntity> userIdMap = new HashMap<>();
                if (StringUtils.isNotEmpty(userList)) {
                    for (UserEntity entity : userList) {
                        accountMap.put(entity.getAccount(), entity);
                        userIdMap.put(entity.getId(), entity);
                    }
                }
                // 当前系统岗位列表
                List<OrganizeEntity> organizeList = organizeService.getList();
                Map<String, OrganizeEntity> organizeMap = new HashMap<>();
                if (StringUtils.isNotEmpty(organizeList)) {
                    for (OrganizeEntity entity : organizeList) {
                        organizeMap.put(entity.getId(), entity);
                    }
                }
                // 当前系统岗位列表
                List<PositionEntity> positionList = positionService.getList();
                Map<String, PositionEntity> positionIdMap = new HashMap<>();
                if (StringUtils.isNotEmpty(positionList)) {
                    for (PositionEntity entity : positionList) {
                        positionIdMap.put(entity.getFullName() + targetChar + entity.getOrganizeId(), entity);
                    }
                }

                // 当前指定数据类型的数据列表
                // 1:企业微信;2:用户
                Map<String, SynThirdInfoEntity> thirdMap = new HashMap<>();
                List<SynThirdInfoEntity> list1 = synThirdInfoService.getList(THIRD_TYPE_QY, DATA_TYPE_USER);
                if (StringUtils.isNotEmpty(list1)) {
                    for (SynThirdInfoEntity entity : list1) {
                        thirdMap.put(entity.getThirdObjectId(), entity);
                    }
                }

                // 用户默认角色
                List<RoleEntity> roleList = roleService.getListByEnCode(SIMPLE_USER);
                String defaultRoleId = "";
                if (StringUtils.isNotEmpty(roleList)) {
                    defaultRoleId = roleList.get(0).getId();
                }
                StringBuilder deptListMsg = new StringBuilder();
                StringBuilder userListMsg = new StringBuilder();
                List<UserEntity> userBatch = new ArrayList<>();
                List<SynThirdInfoEntity> synThirdInfoBatch = new ArrayList<>();
                Map<String, UserEntity> updateUserMap = new HashMap<>();
                Map<String, UserEntity> saveUserMap = new HashMap<>();
                Map<String, SynThirdInfoEntity> updateThirdMap = new HashMap<>();
                Map<String, SynThirdInfoEntity> saveThirdMap = new HashMap<>();
                List<PositionEntity> positionBatch = new ArrayList<>();
                Map<String, PositionEntity> updatePositionMap = new HashMap<>();
                Map<String, PositionEntity> savePositionMap = new HashMap<>();
                for (Object obj : agentPermArr) {
                    String agentPerm = String.valueOf(obj);
                    /**
                     * 获取互联企业部门列表
                     * departmentId：wh87896fbeb5dcdd15/1
                     */
                    // 接口请求结果
                    JSONObject departmentRes = SynQyWebChatUtil.getLinkedcorpDepartment(access_token, agentPerm);
                    if (!departmentRes.getBoolean("code")) {
                        deptListMsg.append(agentPerm);
                        deptListMsg.append(":获取互联企业部门列表失败");
                        // 结束进入下一次循环
                        continue;
                    }
                    String departmentList = String.valueOf(departmentRes.get("departmentList"));
                    List<WeChatDepartment> jsonToList = JsonUtil.getJsonToList(departmentList, WeChatDepartment.class);
                    if (jsonToList.size() != 0) {

                        for (WeChatDepartment o : jsonToList) {
                            /**
                             * 获取互联企业部门成员详情
                             * departmentId：wh87896fbeb5dcdd15/1
                             */
                            // 部门ID
                            String departmentId = o.getDepartment_id();
                            departmentId = agentPerm.replaceFirst("/.*", targetChar + departmentId);
                            JSONObject userListRes = SynQyWebChatUtil.getLinkedcorpUser(access_token, departmentId);
                            if (!userListRes.getBoolean("code")) {
                                userListMsg.append(departmentId);
                                userListMsg.append(":获取互联企业部门成员详情失败");
                                // 结束进入下一次循环
                                continue;
                            }
//                            JSONObject jo = JSONObject.parseObject(String.valueOf(userListRes));
                            String userlist = String.valueOf(userListRes.get("userlist"));
                            List<QyLinkUserEntity> qyUserList = JsonUtil.getJsonToList(userlist, QyLinkUserEntity.class);
                            if (qyUserList.size() != 0) {
                                for (QyLinkUserEntity qyuser : qyUserList) {
                                    String corpid = qyuser.getCorpid();
                                    String userid = qyuser.getUserid();
                                    String mobile = qyuser.getMobile();
                                    String email = qyuser.getEmail();
                                    // 判断是不是为空,需要挨个判断
                                    if (StringUtils.isEmpty(corpid) || StringUtils.isEmpty(userid)) {
                                        // 结束进入下一次循环
                                        continue;
                                    }
                                    UserEntity userEntity;
                                    SynThirdInfoEntity synThirdInfoEntity;
                                    boolean userIsNull = false;
                                    // 第三方表base_sync_third_info第三对象IDthird_object_id
                                    String thirdObjid = corpid + targetChar + userid;
                                    // 1:企业微信;2:用户
//                                    SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoByThirdObjId(THIRD_TYPE_QY, DATA_TYPE_USER, thirdObjid);
                                    if (thirdMap.containsKey(thirdObjid)) {
                                        // 第三方数据已同步
                                        synThirdInfoEntity = thirdMap.get(thirdObjid);
                                        String systemObjectId = synThirdInfoEntity.getSystemObjectId();
                                        if (userIdMap.containsKey(systemObjectId)) {
                                            // 系统用户ID存在
                                            userEntity = userIdMap.get(systemObjectId);
                                        } else {
                                            // 系统用户ID不存在，新增系统用户
                                            if (StringUtils.isNotEmpty(mobile) && accountMap.containsKey(mobile)) {
                                                // 手机号做为登录账户已存在
                                                userEntity = accountMap.get(mobile);
                                            } else if (StringUtils.isNotEmpty(email) && accountMap.containsKey(email)) {
                                                // 邮箱做为登录账户已存在
                                                userEntity = accountMap.get(email);
                                            }  else if (StringUtils.isNotEmpty(userid) && accountMap.containsKey(userid)) {
                                                // userid做为登录账户已存在
                                                userEntity = accountMap.get(userid);
                                            } else {
                                                // 登录账户不存在, 新增系统用户
                                                userIsNull = true;
                                                userEntity = new UserEntity();
                                                userEntity.setId(RandomUtil.uuId());
                                                // 账户account
                                                String account = StringUtils.isNotEmpty(mobile) ? mobile : StringUtils.isNotEmpty(email) ? email : userid;
                                                userEntity.setAccount(account);
                                            }
                                        }
                                    } else {
                                        // 第三方数据未同步
                                        // 不存在 则创建。 “第三方工具的公司-部门-用户同步表模型”
                                        synThirdInfoEntity = new SynThirdInfoEntity();
                                        synThirdInfoEntity.setId(RandomUtil.uuId());
                                        synThirdInfoEntity.setThirdType(Integer.valueOf(THIRD_TYPE_QY));
                                        synThirdInfoEntity.setDataType(Integer.valueOf(DATA_TYPE_USER));
                                        synThirdInfoEntity.setThirdObjectId(thirdObjid);

                                        if (StringUtils.isNotEmpty(mobile) && accountMap.containsKey(mobile)) {
                                            // 手机号做为登录账户已存在
                                            userEntity = accountMap.get(mobile);
                                        } else if (StringUtils.isNotEmpty(email) && accountMap.containsKey(email)) {
                                            // 邮箱做为登录账户已存在
                                            userEntity = accountMap.get(email);
                                        }  else if (StringUtils.isNotEmpty(userid) && accountMap.containsKey(userid)) {
                                            // userid做为登录账户已存在
                                            userEntity = accountMap.get(userid);
                                        } else {
                                            // 登录账户不存在, 新增系统用户
                                            userIsNull = true;
                                            userEntity = new UserEntity();
                                            userEntity.setId(RandomUtil.uuId());
                                            // 账户account
                                            String account = StringUtils.isNotEmpty(mobile) ? mobile : StringUtils.isNotEmpty(email) ? email : userid;
                                            userEntity.setAccount(account);
                                        }
                                    }
                                    synThirdInfoEntity.setCropId(corpid);
                                    synThirdInfoEntity.setSystemObjectId(userEntity.getId());

                                    // 姓名
                                    if (StringUtils.isNotEmpty(qyuser.getName())) {
                                        // 去掉除汉字以外的字符
                                        String name = StringUtils.stringFilter(EmojiUtil.removeAllEmojis(qyuser.getName()));
                                        userEntity.setRealName(name);
                                    }
                                    // 手机
                                    if (StringUtils.isNotEmpty(qyuser.getMobile())) {
                                        userEntity.setMobilePhone(qyuser.getMobile());
                                    }
                                    // 电话
                                    if (StringUtils.isNotEmpty(qyuser.getTelephone())) {
                                        userEntity.setTelePhone(qyuser.getTelephone());
                                    }
                                    // 邮箱
                                    if (StringUtils.isNotEmpty(qyuser.getEmail())) {
                                        userEntity.setEmail(qyuser.getEmail());
                                    }

                                    // 企业微信返回的position是一个岗位名称
                                    String position = qyuser.getPosition();
                                    // 岗位处理验证系统是否存在
//                                    String poitionKey = position + deptId;
//                                    if (positionIdMap.containsKey(poitionKey)) {
//                                        // 存在
//                                        userEntity.setPositionId();
//                                    } else {
//
//                                        if (savePositionMap.containsKey(poitionKey)) {
//                                            // 存在
//                                            PositionEntity posEntity = new PositionEntity();
//                                            posEntity.setId(RandomUtil.uuId());
//                                            posEntity.setFullName(position);
//                                            posEntity.setOrganizeId(deptId);
//                                            // 岗位信息加入待保存列表
//                                            savePositionMap.put(poitionKey, posEntity);
//                                        }
//                                    }
                                    // 企业微信返回的department是一个数组
                                    if (StringUtils.isNotEmpty(qyuser.getDepartment())) {
                                        List deptList = qyuser.getDepartment();
                                        String deptIds = "";
                                        String poitionIds = "";
                                        for (Object deptObj : deptList) {
                                            String cropDept = String.valueOf(deptObj);
                                            String[] cropDeptArr = cropDept.split(targetChar);
                                            String deptId = cropDeptArr[cropDeptArr.length - 1];
                                            if (organizeMap.containsKey(deptId)) {
                                                // 系统存在组织信息
                                                deptIds += deptId + regexChar;
                                                if(StringUtils.isNotEmpty(position)){
                                                    // 企业微信 岗位信息不为空
                                                    poitionIds += position + targetChar + deptId + regexChar;
                                                }
                                            }

                                        }
                                        if (StringUtils.isNotEmpty(deptIds)) {
                                            deptIds = deptIds.substring(0, deptIds.length() - 1);
                                        }
                                        if (StringUtils.isNotEmpty(poitionIds)) {
                                            poitionIds = poitionIds.substring(0, poitionIds.length() - 1);
                                        }
                                        userEntity.setOrganizeId(deptIds);
                                        userEntity.setPositionId(poitionIds);
                                    }
                                    // 企业微信返回的extattr扩展属性中寻找工号进行设置
                                    if (StringUtils.isNotEmpty(qyuser.getExtattr())) {
                                        String extattr = qyuser.getExtattr();
                                        JSONObject jsonObject = JSONObject.parseObject(extattr);
                                        JSONArray attrs = jsonObject.getJSONArray("attrs");
                                        if (attrs.size() != 0) {
                                            for (int i = 0; i < attrs.size(); i++) {
                                                JSONObject attr = attrs.getJSONObject(i);
                                                String name = attr.getString("name");
                                                if (StringUtils.isNotEmpty(name) && name.contains("工号")) {
                                                    userEntity.setCode(attr.getString("value"));
                                                }
                                            }
                                        }
                                    }
                                    // 自定义员工编号，根据组织id获取所属公司。
//                                    if (ObjectUtil.isNotEmpty(o.getDepartment_id())) {
//                                        OrganizeEntity info = organizeService.getInfo(o.getDepartment_id());
//                                        if (ObjectUtil.isNotEmpty(info)) {
//                                            String[] split = info.getOrganizeIdTree().split(regexChar);
//                                            if (split.length > 1) {
//                                                OrganizeEntity companyInfo = organizeService.getInfo(info.getOrganizeId());
//                                                String enCode = companyInfo.getEnCode() + "Staff";
//                                                userEntity.setCode(baseDataUtil.getBillNumber(enCode, false));
//                                            }
//                                        }
//                                    }

                                    if (userIsNull){
                                        // 角色默认
                                        userEntity.setRoleId(defaultRoleId);
                                        // 头像默认  微信企业没传
                                        userEntity.setHeadIcon("/api/file/Image/userAvatar/001.png");
                                        // 性别默认 （1:男；3:女；3:保密）
                                        userEntity.setGender(3);
                                        // 有效标志默认
                                        userEntity.setEnabledMark(1);
                                        // 秘钥默认
                                        userEntity.setSecretkey(RandomUtil.uuId());
                                        // 是否管理员默认 0:否；1:是
                                        userEntity.setIsAdministrator(0);
                                        // 账户密码默认
                                        userEntity.setPassword(userService.getDefaultPassword(userEntity.getSecretkey()));
                                        // 岗位主键
//                                        if (StringUtils.isNotEmpty(qyuser.getPosition())) {
//                                            userEntity.setPositionId(qyuser.getPosition());
//                                        }

                                        if (saveUserMap.containsKey(userEntity.getAccount())) {
                                            // 待保存的Map中存在, 合并到一个user
                                            UserEntity aUser = saveUserMap.get(userEntity.getAccount());
                                            // 合并组织
                                            String orgId1 = aUser.getOrganizeId();
                                            String[] arr1 = StringUtils.isNotEmpty(orgId1) ? orgId1.split(regexChar) : new String[0];
                                            // userEntity
                                            String orgId2 = userEntity.getOrganizeId();
                                            String[] arr2 = StringUtils.isNotEmpty(orgId2) ? orgId2.split(regexChar) : new String[0];
                                            // 合并,去重,set组织
                                            String[] arrAll = ArrayUtil.addAll(arr1, arr2);
                                            String[] distinct = ArrayUtil.distinct(arrAll);
//                                            List<String> existOrgList = new ArrayList<>();
//                                            for (int i = 0; i <distinct.length; i++) {
//                                                if (organizeMap.containsKey(distinct[i])) {
//                                                    existOrgList.add(distinct[i]);
//                                                }
//                                            }
//                                            String orgId3 = String.join(regexChar,existOrgList);
                                            String orgId3 = ArrayUtil.join(distinct,regexChar);
                                            aUser.setOrganizeId(orgId3);

                                            // 合并岗位
                                            String posId1 = aUser.getPositionId();
                                            String[] posArr1 = StringUtils.isNotEmpty(posId1) ? posId1.split(regexChar) : new String[0];
                                            String posId2 = aUser.getPositionId();
                                            String[] posArr2 = StringUtils.isNotEmpty(posId2) ? posId2.split(regexChar) : new String[0];
                                            // 合并,去重,set岗位
                                            String[] posArrAll = ArrayUtil.addAll(posArr1, posArr2);
                                            String[] distinctPos = ArrayUtil.distinct(posArrAll);
                                            String posId3 = ArrayUtil.join(distinctPos,regexChar);
                                            userEntity.setPositionId(posId3);

                                            // 设置同步到系统用户表ID
                                            synThirdInfoEntity.setSystemObjectId(aUser.getId());
                                        } else {
                                            // 放入待保存的Map
                                            saveUserMap.put(userEntity.getAccount(), userEntity);
                                        }

                                        // 设置同步状态值
                                        synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK);
                                        // 放入待保存的Map
                                        saveThirdMap.put(thirdObjid, synThirdInfoEntity);
                                    } else {
                                        // 系统用户systemObjectId或登录账户account已存在
                                        if (updateUserMap.containsKey(userEntity.getAccount())) {
                                            // 待更新的Map中存在
                                            UserEntity aUser = updateUserMap.get(userEntity.getAccount());
                                            String orgId1 = aUser.getOrganizeId();
                                            String[] arr1 = StringUtils.isNotEmpty(orgId1) ? orgId1.split(regexChar) : new String[0];
                                            // userEntity
                                            String orgId2 = userEntity.getOrganizeId();
                                            String[] arr2 = StringUtils.isNotEmpty(orgId2) ? orgId2.split(regexChar) : new String[0];
                                            // 合并去重 组织
                                            String[] arrAll = ArrayUtil.addAll(arr1, arr2);
                                            String[] distinct = ArrayUtil.distinct(arrAll);
//                                            List<String> existOrgList = new ArrayList<>();
//                                            for (int i = 0; i <distinct.length; i++) {
//                                                if (organizeMap.containsKey(distinct[i])) {
//                                                    existOrgList.add(distinct[i]);
//                                                }
//                                            }
//                                            String orgId3 = String.join(regexChar,existOrgList);
                                            String orgId3 = ArrayUtil.join(distinct,regexChar);
                                            aUser.setOrganizeId(orgId3);

                                            // 设置同步到系统用户表ID
                                            synThirdInfoEntity.setSystemObjectId(aUser.getId());
                                        } else {
                                            // 放入待更新的Map
                                            updateUserMap.put(userEntity.getAccount(), userEntity);
                                        }

                                        // 设置同步状态值
                                        synThirdInfoEntity.setSynState(SynThirdConsts.SYN_STATE_OK);
                                        // 放入待保存的Map
                                        updateThirdMap.put(thirdObjid, synThirdInfoEntity);
                                    }
                                }
                            } else {
                                userListMsg.append(departmentId);
                                userListMsg.append(":获取互联企业部门成员详情为空");
                            }
                        }
                    } else {
                        deptListMsg.append(agentPerm);
                        deptListMsg.append(":获取互联企业部门列表为空");
                    }
                }
                log.debug("===========同步企业微信用户信息反馈===========deptListMsg"+deptListMsg);
                log.debug("===========同步企业微信用户信息反馈===========userListMsg"+userListMsg);

                // 检查该 HashMap 是否含有元素
                if (!saveUserMap.isEmpty()) {
                    Iterator<String> iterator = saveUserMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        UserEntity entity = saveUserMap.get(key);
                        // 岗位名称转换positionId
                        String positionId = entity.getPositionId();
                        String[] posArr = StringUtils.isNotEmpty(positionId) ? positionId.split(regexChar) : new String[0];
                        int posLength = posArr.length;
                        String[] positionIdArr = new String[posLength];
                        for (int i = 0; i < posLength; i++) {
                            String poitionKey = posArr[i];
                            if (positionIdMap.containsKey(poitionKey)) {
                                // 存在
                                positionIdArr[i] = positionIdMap.get(poitionKey).getId();
                            } else {
                                if (savePositionMap.containsKey(poitionKey)) {
                                    // 存在
                                    positionIdArr[i] = savePositionMap.get(poitionKey).getId();
                                } else {
                                    // 不存在
                                    if (poitionKey.contains(targetChar)) {
//                                        String[] posDept = poitionKey.split(targetChar);
//                                        String position = posDept[0];
//                                        String deptId = posDept[1];
                                        String position = poitionKey.substring(0, poitionKey.lastIndexOf(targetChar));
                                        String deptId = poitionKey.substring(poitionKey.lastIndexOf(targetChar) + 1);
                                        if (StringUtils.isNotEmpty(position)) {
                                            // 企业微信 岗位信息不为空
                                            PositionEntity posEntity = new PositionEntity();
                                            posEntity.setId(RandomUtil.uuId());
                                            posEntity.setFullName(position);
                                            posEntity.setOrganizeId(deptId);
                                            posEntity.setSortCode(0L);
                                            // 新增岗位信息加入待保存列表
                                            savePositionMap.put(poitionKey, posEntity);
                                            positionIdArr[i] = posEntity.getId();
                                        }
                                    }
                                }
                            }
                        }
                        String posId3 = ArrayUtil.join(positionIdArr,regexChar);
                        entity.setPositionId(posId3);

                        // 将新增用户 加入 批量插入数据库列表
                        userBatch.add(entity);
                    }
                }
                if (!updateUserMap.isEmpty()) {
                    Iterator<String> iterator = updateUserMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        UserEntity entity = updateUserMap.get(key);
                        String organizeIds = ""; // 组织
                        String positionIds = ""; // 岗位
                        String roleIds = ""; // 角色
                        String groupIds = ""; // 分组
                        // 根据用户主键ID 获取用户关系表数据
                        List<UserRelationEntity> relationList = userRelationService.getListByUserId(entity.getId());
                        if (StringUtils.isNotEmpty(relationList)) {
                            for (UserRelationEntity item : relationList) {
                                switch (item.getObjectType()){
//                                    case ORGANIZE:
//                                        organizeIds += item.getObjectId() + regexChar;
//                                        break;
//                                    case POSITION:
//                                        positionIds += item.getObjectId() + regexChar;
//                                        break;
                                    case ROLE:
                                        roleIds += item.getObjectId() + regexChar;
                                        break;
                                    case GROUP:
                                        groupIds += item.getObjectId() + regexChar;
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
//                        entity.setOrganizeId(organizeIds); // 注释原因:不保留系统配置,以企业微信为准
//                        entity.setPositionId(positionIds); // 注释原因:不保留系统配置,以企业微信为准
                        entity.setRoleId(roleIds); // 保留系统配置
                        entity.setGroupId(groupIds); // 保留系统配置

                        // 岗位名称转换positionId
                        String positionId = entity.getPositionId();
                        String[] posArr = StringUtils.isNotEmpty(positionId) ? positionId.split(regexChar) : new String[0];
                        int posLength = posArr.length;
                        String[] positionIdArr = new String[posLength];
                        for (int i = 0; i < posLength; i++) {
                            String poitionKey = posArr[i];
                            if (positionIdMap.containsKey(poitionKey)) {
                                // 存在
                                positionIdArr[i] = positionIdMap.get(poitionKey).getId();
                            } else {
                                if (savePositionMap.containsKey(poitionKey)) {
                                    // 存在
                                    positionIdArr[i] = savePositionMap.get(poitionKey).getId();
                                } else {
                                    // 不存在
                                    if (poitionKey.contains(targetChar)) {
//                                        String[] posDept = poitionKey.split(targetChar);
//                                        String position = posDept[0];
//                                        String deptId = posDept[1];
                                        String position = poitionKey.substring(0, poitionKey.lastIndexOf(targetChar));
                                        String deptId = poitionKey.substring(poitionKey.lastIndexOf(targetChar) + 1);
                                        if (StringUtils.isNotEmpty(position)) {
                                            // 企业微信 岗位信息不为空
                                            PositionEntity posEntity = new PositionEntity();
                                            posEntity.setId(RandomUtil.uuId());
                                            posEntity.setFullName(position);
                                            posEntity.setOrganizeId(deptId);
                                            posEntity.setSortCode(0L);
                                            // 新增岗位信息加入待保存列表
                                            savePositionMap.put(poitionKey, posEntity);
                                            positionIdArr[i] = posEntity.getId();
                                        }
                                    }
                                }
                            }
                        }
                        String posId3 = ArrayUtil.join(positionIdArr,regexChar);
                        entity.setPositionId(posId3);

                        // 将更新用户 加入 批量插入数据库列表
                        userBatch.add(entity);
                    }
                }
                if (!saveThirdMap.isEmpty()) {
                    Iterator<String> iterator = saveThirdMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        synThirdInfoBatch.add(saveThirdMap.get(key));
                    }
                }
                if (!updateThirdMap.isEmpty()) {
                    Iterator<String> iterator = updateThirdMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        synThirdInfoBatch.add(updateThirdMap.get(key));
                    }
                }
                if (!savePositionMap.isEmpty()) {
                    Iterator<String> iterator = savePositionMap.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        positionBatch.add(savePositionMap.get(key));
                    }
                }
                if (StringUtils.isNotEmpty(userBatch) && StringUtils.isNotEmpty(synThirdInfoBatch)) {
                    for (UserEntity entity : userBatch) {
                        // 组织 岗位 角色
                        userService.saveOrUpdateCommon(entity.getId(), entity);
                    }
                    positionService.saveOrUpdateBatch(positionBatch);
                    userService.saveOrUpdateBatch(userBatch);
                    synThirdInfoService.saveOrUpdateBatch(synThirdInfoBatch);
                    //获取结果
                    SynThirdTotal synThirdTotal = synThirdInfoService.getSynTotal(THIRD_TYPE_QY, DATA_TYPE_USER);
                    return ActionResult.success(synThirdTotal);
                } else {
                    return ActionResult.fail("获取用户数据为空");
                }
            } else {
                return ActionResult.fail("获取应用的可见范围为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ActionResult.fail("系统异常：" + e);
        }
    }

}
